package cn.ynu.cmrs;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Application;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.DialogInterface.OnClickListener;
import android.content.SharedPreferences.Editor;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.AssetManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import cn.ynu.cmrs.BuildConfig;
import cn.ynu.cmrs.R;
import cn.ynu.cmrs.activity.LoginActivity;
import cn.ynu.cmrs.model.User;
import cn.ynu.cmrs.utils.ImageCache;

public class MyApplication extends Application {

	/**
	 * DDMS debugging Log output label
	 */
	public static String TAG = "CMRS";

	/**
	 * Application instance
	 */
	private static MyApplication instance;

	/**
	 * The image cache for all Activity
	 */
	private static ImageCache mImageCache;

	/**
	 * ArrayList which used to save all Activity opened during program is
	 * running
	 */
	public static ArrayList<Activity> allActivity = new ArrayList<Activity>();

	/**
	 * User object, save the currently logged in user information
	 */
	public static User nowUser = new User();

	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();
		mImageCache = new ImageCache();
		instance = this;
	}

	public static ImageCache getImageCache() {
		return mImageCache;
	}

	public static MyApplication getInstance() {
		return instance;
	}

	/**
	 * Get the software version number
	 * 
	 * @return Software version number
	 */
	public String getVersion() {
		String version = "0.0.0";
		PackageManager packageManager = getPackageManager();
		try {
			PackageInfo packageInfo = packageManager.getPackageInfo(
					getPackageName(), 0);
			version = packageInfo.versionName;
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}

		return version;
	}

	/**
	 * Exit the program, close all opened Activity and Service
	 * 
	 * @param context
	 *            This context of the Activity or Service which called this
	 *            method
	 */
	public static void exitApp(Context context) {
		for (Activity ac : allActivity) {
			if (BuildConfig.DEBUG) {
				Log.i("Activitys", ac.getClass().toString());
			}
			ac.finish();
		}
		allActivity.clear();
	}

	/**
	 * Protection of exit, pop-up dialog allows the user to confirm the exit
	 * operation
	 * 
	 * @param context
	 *            This context of the Activity which called this method
	 */
	public static void promptExitApp(final Context context) {
		LayoutInflater li = LayoutInflater.from(context);
		View exitV = li.inflate(R.layout.exitdialog, null);
		AlertDialog.Builder ab = new AlertDialog.Builder(context);
		ab.setView(exitV)
				.setPositiveButton(R.string.exitApp, new OnClickListener() {
					public void onClick(DialogInterface arg0, int arg1) {
						exitApp(context);
					}
				}).setNegativeButton(R.string.cancel, null).show();
	}

	/**
	 * Pop-up dialog box prompts the user to network errors, and provide the
	 * appropriate operation
	 * 
	 * @param context
	 */
	public static void alertNetworkError(final Context context) {
		AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
		alertDialog.setTitle(R.string.NetException)
				.setMessage(R.string.NoSignalException)
				.setNegativeButton(R.string.exitApp, new OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						dialog.cancel();
						exitApp(context);
					}
				})
				.setPositiveButton(R.string.setNetwork, new OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
						context.startActivity(new Intent(
								android.provider.Settings.ACTION_WIRELESS_SETTINGS));
					}
				}).create().show();
	}

	/**
	 * Get Activity instance by Activity's name
	 * 
	 * @param name
	 *            Name of Activity
	 * @return Activity instance or null
	 */
	public static Activity getActivityByName(String name) {
		for (Activity ac : allActivity) {
			if (ac.getClass().getName().indexOf(name) >= 0) {
				return ac;
			}
		}
		return null;
	}

	public static void IPConfig(Activity activity) {

		SharedPreferences preferences = activity.getSharedPreferences("cmrs",
				Context.MODE_PRIVATE);
		String appServerIP = preferences.getString("AppServerIP", "");
		String streamServerIP = preferences.getString("StreamServerIP", "");
		AppConstant.URL.BASE_URL = appServerIP;
		AppConstant.URL.RTSP_URL = streamServerIP;
		try {
			AssetManager assetManager = activity.getAssets();
			InputStream is = assetManager.open("config.txt");
			InputStreamReader reader = new InputStreamReader(is);
			BufferedReader buffer = new BufferedReader(reader);
			String line = null;
			while ((line = buffer.readLine()) != null) {
				String[] str = line.split("-");
				if (str[0].equals("AppServerIP")
						&& AppConstant.URL.BASE_URL.equals("")) {
					AppConstant.URL.BASE_URL = str[1];
				} else if (str[0].equals("StreamServerIP")
						&& AppConstant.URL.RTSP_URL.equals("")) {
					AppConstant.URL.RTSP_URL = str[1];
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
